package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponse;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@Controller
public class OAuthLoginController {


    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String oauthLogin(@RequestParam("code") String code, RedirectAttributes attributes, HttpSession session) throws Exception {

        HashMap<String, String> header = new HashMap<>();
        HashMap<String, String> query = new HashMap<>();

        // 根据code换取token
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","");
        map.put("client_secret","");

        HttpResponse post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, query, map);
        if (post.getStatusLine().getStatusCode() == 200) {
            // 成功
            String string = EntityUtils.toString(post.getEntity());
            SocialUser socialUser = JSON.parseObject(string, SocialUser.class);

            // 判断是登录还是注册
            // todo  调用member远程服务，登录或者注册
            R r = memberFeignService.oauth2Login(socialUser);

            if (r.getCode() == 0){
                MemberResponse data = (MemberResponse) r.getData("data", new TypeReference<MemberResponse>() {
                });
                session.setAttribute(AuthServerConstant.SESSION_LOGIN_USER,data);
                System.out.println("登录成功" + data.toString());
                return "redirect:http://gulimall.com";
            }else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", (String) r.get("msg"));
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/login.html";
//                return "login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
//            return "login.html";
        }

    }
}
